Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Web.UI;
- using System.Windows.Forms;
- namespace TreeHierarchyTest
- {
- public partial class TreeViewHierarchyBinding : Component
- {
- private IHierarchyData dataSource;
- private TreeView treeView;
- private Dictionary<TreeNode, IHierarchyData> nodeDictionary = new
- Dictionary<TreeNode, IHierarchyData>();
- public TreeViewHierarchyBinding()
- {
- InitializeComponent();
- }
- public TreeViewHierarchyBinding(IContainer container)
- {
- container.Add(this);
- InitializeComponent();
- }
- #region TreeView Events
- private void RegisterEvents(TreeView tv)
- {
- tv.BeforeExpand += TreeViewBeforeExpand;
- }
- private void UnregisterEvents(TreeView tv)
- {
- tv.BeforeExpand -= TreeViewBeforeExpand;
- }
- private void TreeViewBeforeExpand(object sender, TreeViewCancelEventArgs e)
- {
- if (e.Node.Checked)
- {
- return;
- }
- IHierarchyData hierarchyData;
- if (nodeDictionary.TryGetValue(e.Node, out hierarchyData))
- {
- PopulateChildNodes(e.Node.Nodes, hierarchyData.GetChildren());
- e.Node.Checked = true;
- }
- }
- #endregion
- #region TreeView Population
- private void PopulateChildNodes(TreeNodeCollection parentCollection,
- IHierarchicalEnumerable children)
- {
- parentCollection.Clear();
- foreach (object child in children)
- {
- IHierarchyData childData = children.GetHierarchyData(child);
- TreeNode childNode = new TreeNode(childData.ToString());
- if (childData.HasChildren)
- {
- childNode.Nodes.Add("Dummy"); // Make expandable
- }
- nodeDictionary.Add(childNode, childData);
- parentCollection.Add(childNode);
- }
- }
- private void UpdateRootNodes(TreeView tv, IHierarchyData hierarchyData)
- {
- if (tv == null)
- {
- return;
- }
- tv.Nodes.Clear();
- if (hierarchyData != null)
- {
- IHierarchicalEnumerable roots = hierarchyData.GetChildren();
- PopulateChildNodes(tv.Nodes, roots);
- }
- }
- #endregion
- [Browsable(false)]
- [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public IHierarchyData DataSource
- {
- get { return dataSource; }
- set
- {
- if (value != dataSource)
- {
- dataSource = value;
- nodeDictionary.Clear();
- UpdateRootNodes(treeView, value);
- }
- }
- }
- [Category("Behavior")]
- [DefaultValue(null)]
- [Description("Specifies the TreeView that the hierarchy should be bound to.")]
- public TreeView TreeView
- {
- get { return treeView; }
- set
- {
- if (value != treeView)
- {
- if (treeView != null)
- {
- UnregisterEvents(treeView);
- }
- treeView = value;
- nodeDictionary.Clear();
- RegisterEvents(value);
- UpdateRootNodes(treeView, dataSource);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement